/**
 * 柜面卡交易部分
 */
var TX = {
	TEST_MODE : false// 当TEST_MODE为true的时候,转帐页面会列出可转出的目标
	,
	PAYMENT_TYPE ://需要列出的支付类型
		[Constants.PAYMENT_CASH
		,Constants.PAYMENT_BANK
		//,Constants.PAYMENT_CHEQUE
		]
	,
	SHOW_INFO_LINEBREAK:
		isIE()?"<br>":"\n"
	,
	DEFAULT_CURRENCY : 0//默认人民币
};
TX.STATUS = {
	DEPOSIT ://需要列出充值交易的状态
		[Constants.TRADE_STATUS_NORMAL
		,Constants.TRADE_STATUS_CANCEL
		,Constants.TRADE_STATUS_CANCELED
		,Constants.TRADE_STATUS_TEMP]
	,
	CONSUME ://需要列出充值交易的状态
		[Constants.TRADE_STATUS_NORMAL
		,Constants.TRADE_STATUS_CANCEL
		,Constants.TRADE_STATUS_CANCELED]
	,
	LOAD ://需要列出圈存的状态
		[Constants.TRADE_STATUS_NORMAL
		,Constants.TRADE_STATUS_CANCEL
		,Constants.TRADE_STATUS_CANCELED]
	,
	EXCHANGE ://礼品兑换
		[Constants.TRADE_STATUS_NORMAL
		,Constants.TRADE_STATUS_BOOKING
		,Constants.TRADE_STATUS_INVALIDITY]
};
//押金类型,没有必要区分TYPE和SUBTYPE
TX.SUBTYPE = {
	DEPOSIT: //收款子类型
		[Constants.TRADE_TYPE_CASH_IN
		,Constants.TRADE_TYPE_CHEQUE_IN
		,Constants.TRADE_TYPE_BANK_IN
		,Constants.TRADE_TYPE_RET_CLIENT]
	,
	DRAWBACK: //退款子类型
		[Constants.TRADE_TYPE_CASH_OUT
		//,Constants.TRADE_TYPE_CHEQUE_OUT
		//,Constants.TRADE_TYPE_BANK_OUT
		]
	,
	EXPIRE: //失效清零子类型
		[Constants.TRADE_TYPE_EXPIRE
		,Constants.TRADE_TYPE_CLEAR]
	,
	TRANSFER ://转帐子类型
		[Constants.TRADE_TYPE_TRANSFER_IN
		,Constants.TRADE_TYPE_TRANSFER_OUT
		,Constants.TRADE_TYPE_ORG_DIST_IN
		,Constants.TRADE_TYPE_ORG_DIST_OUT
		,Constants.TRADE_TYPE_ORG_COLLECT_IN
		,Constants.TRADE_TYPE_ORG_COLLECT_OUT
		,Constants.TRADE_TYPE_CREDIT_DEPOSIT_IN
		,Constants.TRADE_TYPE_CREDIT_DEPOSIT_OUT]
	,
	CONSUME ://消费
		[Constants.TRADE_TYPE_CARD_CONSUME
		//,Constants.TRADE_TYPE_SPARE_CONSUME
		,Constants.TRADE_TYPE_CASH_CONSUME
		,Constants.TRADE_TYPE_BANK_CONSUME
		]
	,
	LOAD ://圈提
		[Constants.TRADE_TYPE_LOAD_IN
		,Constants.TRADE_TYPE_UNLOAD_OUT]
};
TX.AccountType ={
	deposit ://可以充值的帐户类型
		function(){
			var check = function(a){
				return (a.canDeposit && a.baseAccountType == BaseAccountType.NORMAL)
			}
			return Account._getAccountTypes(check);
		}
	,
	cardTx ://可以进行卡交易的帐户类型
		function(){
			var check = function(a){
				return (a.hasCardAccount && a.baseAccountType == BaseAccountType.NORMAL)
			}
			return Account._getAccountTypes(check);
		}
	,
	userTx : //可以用户进行交易的帐户类型
		function(){
			var check = function(a){
				return a.baseAccountType == BaseAccountType.NORMAL
			}
			return Account._getAccountTypes(check);
		}
}
TX.List = {};//明细页面
//【交易明细部分】查询明细页面,初始化页面的公共函数
TX.List.init = function(){
	Eui.showNavigation();
	Page = {};//页面元素Page
	Page.form = $("searchForm");
	Page.selection = ListPage._getSelection();
	Page.columns = [];//列表项
	Page.positive = true;//页面金额校验函数限制于正数
	//Page.columns[ListPage.COLUMNS_LENGTH_MAX] = ListPage.Operations.Trade;//设置columns中的操作项
	Page.form.orgID.value = Common.cOrg().id;//设置默认的受理机构ID
	ListPage.initDateSelects();
	initPageElements();//由页面定义的具体初始化内容
	if (Page.columns.length==0){
		if (!Page.operation)//定义页面的“操作”函数
			Page.operation = ListPage.Operations.Trade;
		Page.columns[ListPage.COLUMNS_LENGTH_MAX] = Page.operation;//设置columns中的操作项
	}
	ListPage.initFormElements();
	ListPage.changeAccountCode(null);
	setPages(["listView","detailView"])
};

TX.Trade = {};//有卡交易页面
TX.Trade.init = function(){//初始化
	Eui.showNavigation();
	Page = {};
	Page.raw = {};
	Page.options = {disAppInfo:true,grayStatus:true,disBalance:true,disLoyalty:true,disPersonInfo:true};
	Page.readonlyTableStyle = null;
//	Page.forbiddenStatus = true;
	Page.operationForm = $("operationForm");
	Page.operation = Page.operationForm.operation;
	initPageElements();
	TX.Trade.changeAccCode();
	Page.operation.disabled = true;
	setPages(["operationFormDiv","printSheetDiv","billDiv"]);
	initActiveX();
}
TX.Trade.changeAccCode = function (self){//改变帐户类型
	if (Page.operationForm.accCode)
		Page.accCode = Page.operationForm.accCode.value;
	else
		Page.accCode = AccountType.FUND;//默认为资金帐户
	Page.unit = (Common.getItem('account_type',Page.accCode))["unit"];
	Page.amountValidator = Account.getValidatorByUnit(Page.unit);
	Page.amountInSystem = Account.Transformer.InByAccCode(Page.accCode);
	TX.Trade.CardInfo.showInfo("readonlyInfo",Page.options, Page.raw, Page.accCode ,Page.readonlyTableStyle);
	if(Page.changeAccCode)
		Page.changeAccCode();
}
TX.Trade.ReadCard = function(){
	Page.raw = {};
	try{
		TX.Misc.Timer.init();
		if (Page.options.disLoyalty){
			Page.options.tradeDate = DWR.syncCall("cardMgntService.getServerTime");
		}
		TX.Misc.Timer.add('serverTime');
		Page.raw.card = getCardDetail(Page.options);
		TX.Misc.Timer.add('readCard');
		if(!Page.raw.card)
			return;
		var data = DWR.syncCall("cardMgntService.cardSearch",Page.raw.card.asn);
		TX.Misc.Timer.add('getCardUser');
		//TX.Misc.Timer.print();
		
		var info = TX.Trade.checkCardStatus(Page.raw.card,data);
		if (info){
			showWarning(info);
			Page.operation.disabled = true;
			return;
		}
		Page.raw.user = data;
		if(Page.checkAuthority && !Page.checkAuthority(data)){
			Page.operation.disabled = true;
		}else{
			Page.operation.disabled = false;
		}
	}catch(e){
		showError(e.description);
	}
	TX.Trade.CardInfo.showInfo("readonlyInfo",Page.options, Page.raw, Page.accCode ,Page.readonlyTableStyle);
}

TX.Trade.checkCardStatus = function(card,data){
	var info ='';
	if (data.expired){
		info = "卡片已过有效期,无法进行操作";
	}else if (data.card){
		switch(data.card.status){
			case CardStatus.BLACK:
				info = "卡片在黑名单状态，无法进行操作";
				break;
			case CardStatus.REVOCATION:
			case CardStatus.NOCARD:
				info = "卡片已经注销，无法进行操作";
				break;
			case CardStatus.INITED:
				info = "未发卡卡片，无法进行操作";
				break;
		}
		if (data.currentCard && card.asn!=data.currentCard.asn)
			info = "卡片不是客户的当前卡，无法继续操作";
	}else{
		info = "无法找到相关IC卡";
	}
//	if (!data.currentCard)
//		info = "未发卡卡片，无法继续操作";
//	else if (card.asn!=data.currentCard.asn)
//		info = "卡片不是客户的当前卡，无法继续操作";
//	else{
//		//card = raw.user.currentCard;
//		switch(data.currentCard.status){
//			case CardStatus.BLACK:
//				info = "卡片在黑名单状态，无法进行操作";
//				break;
//			case CardStatus.REVOCATION:
//			case CardStatus.NOCARD:
//				info = "卡片已经注销，无法进行操作";
//				break;
//			case CardStatus.INITED:
//				info = "未发卡卡片，无法进行操作";
//				break;
//		}
//	}
	return info;
}
TX.Trade.reset = function(){
	Page.operationForm.reset();
	TX.Trade.changeAccCode();
	clearErrorView(Page.operationForm.id);
	if (Page.cleanUp)
		Page.cleanUp();
}
TX.Trade.goFirstPage = function(){
	Page.raw = {};
	TX.Trade.reset();
	switchPage("operationFormDiv");
}
TX.Trade.showResult = function(result){
	if (Page.preResult)
		Page.preResult(result);
	//显示凭证
	if (!Page.billOption)
		Page.billOption = {queryName:Page.bill}
	Page.billOption.tradeId = result.id;
	Eui.getBillHtml('content',Page.billOption);
	switchPage("billDiv");
	return;
	if (Page.operation)
		Page.operation.disabled = true;
	if (Page.postResult)
		Page.postResult();
	//自动打印单据
	WebPrint.print('content')
}
//从IC卡读取卡号,并设置到form中.无需密码.
TX.Trade.readAsn = function(){
	var asn;
	try{
		getCard();
		asn = getAsn();
		return asn;
	}catch(e){
		showError(e.description);
		return ""
	}
}
TX.Trade.CardInfo = {};//卡片信息
TX.Trade.CardInfo.getTemplate = function(){
	var map = {};
	var basic = new Array();
	basic.push(["cardAsn","卡&nbsp;&nbsp;&nbsp;&nbsp;号"]);
	basic.push(["cardType","卡 类 型"]);
	basic.push(["cardStatus","卡 状 态"]);
	basic.push(["blackType","黑名单原因",true]);
	basic.push(["cardUserUnique","客户编号"]);
	basic.push(["cardUserStatus","客户状态"]);
	map.basic = basic;
	
	var customer = new Array();
	customer.push(["name","客户姓名"]);
	customer.push(["idno","证 件 号"]);
	map.customer = customer;
	
	var account = new Array();
	account.push(["unit","帐户单位"]);
	account.push(["cardBalance","卡内余额"]);
	account.push(["spareBalance","备用帐户余额"]);
	account.push(["shadowBalance","后台卡帐户余额"]);
	map.account = account;
	return map;
}
TX.Trade.CardInfo.pretreatInfo = function(raw,accountType){
	var data = {};
	if (raw.card){
		data.cardAsn = raw.card.asn;
		if (accountType==AccountType.POINT)
			data.cardBalance = raw.card.cardLoyaltyBalance;
		else
			data.cardBalance = raw.card.cardBalance;
	}
	if (raw.user){
		if (raw.user.accounts){
			var spare = Constants.SPARE_ACCOUNT_PREFIX + accountType;
			if (raw.user.accounts[spare]){
				data.unit = (Common.getItem('account_type',raw.user.accounts[spare].type))["unit"]; 
				data.spareBalance = raw.user.accounts[spare].balance;
			}
			var card = Constants.CARD_ACCOUNT_PREFIX + accountType;
			if (raw.user.accounts[card])
				data.shadowBalance = raw.user.accounts[card].balance;
		}
		data.cardType = raw.user.cardTypeName;
		if (data.cardAsn==raw.user.currentCard.asn){
			data.cardStatus = raw.user.currentCard.status;
			data.blackType = raw.user.currentCard.blackType;
		}else{
			//如果卡片不是当前卡
			//data.cardStatus = 
		}
		data.cardUserUnique = raw.user.cardUser.uniqueId;
		data.cardUserStatus = raw.user.cardUser.status;
		if (raw.user.customer){
			data.name = raw.user.customer.name;
			data.idno = raw.user.customer.idno;
		}
	}
	var renders = {cardBalance:Format.fenToYuan,spareBalance:Format.fenToYuan,
					shadowBalance:Format.fenToYuan};
	for (var x in renders)
		if (typeof renders[x] == "function" && data[x]!=null && typeof data[x]!="function"){
			data[x] = renders[x](data[x]);
		}
	var dicts = {unit:"account_unit",cardUserStatus:"carduser_status"
				,cardStatus:"card_status",blackType:"black_type",accountType:"account_type"};//
	for (var x in dicts)
		if (typeof dicts[x] != "function" && dicts[x]){
			data[x] = Common.getText(dicts[x],data[x]);
		}
	return data;
}
TX.Trade.CardInfo.showInfo = function (showDivId,options,values,accountType,style){
	var CARDUSER_INFO = TX.Trade.CardInfo.getTemplate();
	if (!style)
		style = 'col2 label8';
	var str = "<table cellSpacing='0' cellPadding='4' width='100%' border='0' class='"+style+"'>";
	var data = TX.Trade.CardInfo.pretreatInfo(values,accountType);
	var render = new DataRender(DataRender.LabelAndInput,data);
	render.skipBlank = false;
	if (options.disAppInfo)
		str += render.getItemsShowString(CARDUSER_INFO.basic);
	if (options.disPersonInfo)
		str += render.getItemsShowString(CARDUSER_INFO.customer);
	if (options.disBalance || options.disLoyalty)
		str += render.getItemsShowString(CARDUSER_INFO.account);
	str += "</table>";
	$(showDivId).innerHTML = str;
}



TX.NoCardTrade = {};//无卡交易页面
TX.NoCardTrade.init = function(){
	Eui.showNavigation();
	Page = {};
	Page.readonlyTableStyle = 'col2 label5';
	Page.forbiddenStatus = true;//客户状态异常时禁止操作
	Page.hideBalance = false;//不显示帐户余额
	Page.searchForm = $("searchForm");
	Page.operationForm = $("operationForm");
	initPageElements();
	setPages(["searchFormDiv","operationFormDiv","printSheetDiv","billDiv"]);
	initActiveX();
}
//查询帐户信息
TX.NoCardTrade.getUserAccountInfo = function(){
	if(!checkForm(Page.searchForm.id))
		return;
	if (!TX.Misc.hasAny([Page.searchForm.asn,Page.searchForm.cardUserUnique])){
		try{
			getCard();
			Page.searchForm.asn.value = getAsn();
		}catch(e){
			showWarning("卡号或客户编号必须输入其一")
			return;
		}
	}
	DWR.call("cardMgntService.getUserInfo",
				Page.searchForm.asn.value,
				Page.searchForm.cardUserUnique.value,
				function(result){
					if (result.cardUser.status==CardUserStatus.REVOCATION){
						showWarning("客户已经注销，无法进行操作");
						return;
					};//后台可以提供一个统一的expired的方法
					if (result.card && result.cardUser.type!=CardUserType.COMPANY 
						&& result.card.asn != result.currentCard.asn){
							showWarning("卡片不是客户的当前卡，无法继续操作");
							return;
					}
					if (Page.forbiddenStatus){
						var info = TX.NoCardTrade.checkUserStatus(result.cardUser);
						if (info){
							showWarning(info);
							return;
						}
					}
					if(Page.initOperationForm && !Page.initOperationForm(result))
						return;
					Page.userInfo = result;
					TX.NoCardTrade.changeAccCode(null);
					switchPage("operationFormDiv");
				},
				{disCtrl:Page.searchForm.search}
			);
}
TX.NoCardTrade.checkUserStatus = function(cardUser){
	var info ='';
	switch(cardUser.status){
		case CardUserStatus.BLACK:
			info = "客户帐户被冻结，请先进行解冻操作";
			break;
		case CardUserStatus.REVOCATION:
			info = "客户已经注销，无法进行操作";
			break;
		case CardUserStatus.UNACTIVATED:
		case CardUserStatus.CUSTOMIZE:
			info = "客户未激活，无法进行操作"
			break;
	}
	return info;
}
TX.NoCardTrade.changeAccCode = function (self){
	if (Page.operationForm.accCode)
		Page.accCode = Page.operationForm.accCode.value;
	else
		Page.accCode = AccountType.FUND;//默认为资金帐户
	var unit = (Common.getItem('account_type',Page.accCode))["unit"];
	Page.amountValidator = Account.getValidatorByUnit(unit);
	Page.amountInSystem = Account.Transformer.InByAccCode(Page.accCode);
	if (!Page.userInfo)
		return;
	TX.NoCardTrade.CardUser.showUserInfo("readonlyInfo", Page.userInfo, Page.hideBalance?'NULL':Page.accCode, Page.readonlyTableStyle);
	if(Page.changeAccCode)
		Page.changeAccCode();
}
TX.NoCardTrade.goFirstPage = function (){
	if(Page.cleanUp)
		Page.cleanUp();
	Page.searchForm.reset();
	Page.operationForm.reset();
	Page.operationForm.operation.disabled = false;
	clearErrorView(Page.operationForm.id);
	switchPage("searchFormDiv");
}

TX.NoCardTrade.CardUser = {};//柜面交易获取CardUsr信息
TX.NoCardTrade.CardUser.getTemplate = function(){
	var map = {};
	var basic = new Array();
	basic.push(["cardUserUnique","客户编号"]);
	basic.push(["cardUserStatus","客户状态"]);
	basic.push(["cardAsn","卡&nbsp;&nbsp;&nbsp;&nbsp;号"]);
	basic.push(["cardType","卡 类 型"]);
	basic.push(["mainCard","主卡卡号"]);
	map.basic = basic;
	
	var customer = new Array();
	customer.push(["name","客户姓名"]);
	customer.push(["idno","证 件 号"]);
	map.customer = customer;
	
	var companyCustomer = new Array();
	companyCustomer.push(["companyName","单位名称"]);
	companyCustomer.push(["companyIdno","单位证件号"]);
	map.companyCustomer = companyCustomer;
	
	var account = new Array();
	account.push(["unit","帐户单位"]);
	account.push(["balance","帐户余额"]);
	map.account = account;
	return map;
}
TX.NoCardTrade.CardUser.pretreatInfo = function(values,accountType){
	var data = {};
	if (values.cardUser){
		data.cardUserUnique = values.cardUser.uniqueId;
		data.cardUserStatus = values.cardUser.status;
	}
	if (values.currentCard){
		data.cardAsn = values.currentCard.asn;
		data.cardType = values.cardTypeName;
	}
	if (values.mainCard)
		data.mainCard = values.mainCard.asn;
	if (values.customer){
		data.name = values.customer.name;
		data.idno = values.customer.idno;
	}
	if (values.companyCustomer){
		data.companyName = values.companyCustomer.name;
		data.companyIdno = values.companyCustomer.idno;
	}
	var spare = Constants.SPARE_ACCOUNT_PREFIX + accountType;
	if (values.accounts[spare]){
		data.unit = (Common.getItem('account_type',values.accounts[spare].type))["unit"]; 
		data.balance = values.accounts[spare].balance;
	}
	var renders = {balance:Format.fenToYuan}//{balance:Account.Transformer.OutByUnit(data.unit)}
	for (var x in renders)
		if (typeof renders[x] == "function" && data[x]!=null && typeof data[x]!="function"){
			data[x] = renders[x](data[x]);
		}
	var dicts = {unit:"account_unit",cardUserStatus:"carduser_status",accountType:"account_type"};
	for (var x in dicts)
		if (typeof dicts[x] != "function" && dicts[x]){
			data[x] = Common.getText(dicts[x],data[x]);
		}
	return data;
}
TX.NoCardTrade.CardUser.showUserInfo = function (showDivId,values,accountType,style){
	var CARDUSER_INFO = TX.NoCardTrade.CardUser.getTemplate();
	if (!style)
		style = 'col2 label5';
	var str = "<table cellSpacing='0' cellPadding='4' width='100%' border='0' class='"+style+"'>";
	var data = TX.NoCardTrade.CardUser.pretreatInfo(values,accountType);
	var render = new DataRender(DataRender.LabelAndInput,data);
	render.skipBlank = true;
	str += render.getItemsShowString(CARDUSER_INFO.basic);
	if (data.name)
		str += render.getItemsShowString(CARDUSER_INFO.customer);
	if (data.companyName)
		str += render.getItemsShowString(CARDUSER_INFO.companyCustomer);
	if (data.unit)
		str += render.getItemsShowString(CARDUSER_INFO.account);
	str += "</table>";
	$(showDivId).innerHTML = str;
}

TX.Template = {//模板页面
	HEIGHT : 400,//编辑模板的窗口高
	WIDTH : 800  //窗口宽
}
//Edit a template
TX.Template.open = function(){
	var v = openDialogFrame('/trade/distribute_template.html?templateId='+Page.templateId,
				'单位模板维护',TX.Template.HEIGHT,TX.Template.WIDTH);
	if (v){
		TX.Template.list();
	}
	return false;
}
//List all the templates
TX.Template.list = function(){
	DWR.call("txQueryService.getDistributeTemplates",
			Page.userInfo.cardUser.id,
			Page.operationForm.accCode.value,
			Page.distribute,
			function(v){
				Page.dtSelection = [];
				Page.templates = {};
				for (var x in v){
					if(v[x] && typeof v[x]!= 'function'){
						Page.dtSelection.push({code:v[x].id,text:v[x].name});
						Page.templates[v[x].id] = v[x];
					}
				}
				Common.initDict(Page.operationForm.templateId,Page.dtSelection);
				TX.Template.load();
			}
	);
}
//Loat the selected template
TX.Template.load = function(){
	Page.templateId = Page.operationForm.templateId.value;
	var dt = Page.templates[Page.templateId];
	Page.operationForm.templateTime.value = Format.timeRender(dt.lastModified);
	Page.templateAmounts = DWR.syncCall("txQueryService.loadDistributeAmounts",Page.operationForm.templateId.value);
	if (Page.templateFilter)
		Page.templateFilter();
	else
		Page.operationForm.amount.value = Account.Transformer.OutByAccCode(Page.accCode)(dt.amount);
	var str = DetailPage.Misc.List2Table(Page.templateAmounts,Page.templateItems,DetailPage._transferTradeDetails);
	$("templateDetails").innerHTML = str;
}
TX.Invoice = {
	TYPE :
		[InvoiceType.DEPOSIT
		//,InvoiceType.CONSUME
		,InvoiceType.VAT
		,InvoiceType.DEPOSIT_BACK
		]
	,
	CARDUSERTYPE :
		[CardUserType.NAME
		,CardUserType.COMPANY
		//,CardUserType.DRIVER
		]
};
TX.Invoice.doSave = function (service,confirmString){
	if(!checkForm(operationForm))
		return;
	var data = Common.getValues(Page.operationForm);
	if(showQuestion(confirmString)){
		DWR.call(service,
				data.cardUserUnique,
				data.cardAsn,
				Page.amountInSystem(data.amount),
				function(result){
					showInformation("保存成功");
					TX.NoCardTrade.goFirstPage();
				},
				{disCtrl:Page.operationForm.operation}
			);
	}else{
		Page.operationForm.amount.value="";
		Page.operationForm.amount.focus();
	}
}
TX.Invoice.offer = function(){
	var confirmString = "确认开票金额:" + Page.operationForm.amount.value + "元？";
	TX.Invoice.doSave("invoiceService.recordInvoiceAmount",confirmString);
}
TX.Invoice.drawback = function(){
	var confirmString = "确认退发票金额:" + Page.operationForm.amount.value + "元？";
	TX.Invoice.doSave("invoiceService.backInvoice",confirmString);
}
TX.Invoice.saveInvoice = function(cardUserUnique, asn, amount){
	var confirmString = "是否开发票?";
	if(showQuestion(confirmString)){
		DWR.call("invoiceService.recordInvoiceAmount",
				cardUserUnique,
				asn,
				amount,
				function(result){
					showInformation("保存发票金额成功");
				}
			);
	}
}
TX.Shift = {}
TX.Shift.getTemplate = function (){
	var basic = new Array();
	//basic.push(["org","机构编号"]);
	basic.push(["businessDate","业务日期"]);
	basic.push(["shiftNo","班 次 号"]);
	basic.push(["shiftStatus","班结状态"]);
	basic.push(["oper","管理员编号"]);
	basic.push(["startTime","开班时间"]);
	basic.push(["endTime","结班时间"]);
	basic.push(["prepareTime","预计结班时间"]);
	return basic;
}
TX.Shift.showDetail = function (data,div){
	var str = "<table cellSpacing='0' cellPadding='4' width='100%' border='0' class='col2 label6'>";
	var renders = {businessDate:Format.dateRender,startTime:Format.timeRender,
				endTime:Format.timeRender,prepareTime:Format.timeRender};
	for (var x in renders)
		if (typeof renders[x] == "function" && data[x]!=null && typeof data[x]!="function")
			data[x] = renders[x](data[x]);
	var dicts = {shiftStatus:"shift_status"};
	for (var x in dicts)
		if (typeof dicts[x] != "function" && dicts[x])
			data[x] = Common.getText(dicts[x],data[x]);
	var render = new DataRender(DataRender.LabelAndInput,data);
	render.skipBlank = true;
	str += render.getItemsShowString(TX.Shift.getTemplate());
	str += "</table>";
	$(div).innerHTML = str;
}
TX.Shift.showShiftChecks = function(shiftId){
	TX.Shift._showChecks({shiftId:shiftId});
}
TX.Shift._showChecks = function(param){
	//param.itemType = 1;
	//TX.Shift._showSingleCheck(param,"cardType;cardStatus","|openingSum;closingSum;cardSum;count","card");
	TX.Shift._showCardChecks(param);
	param.itemType = 2;
	TX.Shift._showSingleCheck(param,"tradeType;tradeStatus","|sum;count","trade");
	param.itemType = 3;
	TX.Shift._showSingleCheck(param,"invoiceType","|invoiceSum;invoiceCount","invoice");
}
TX.Shift._showCardChecks = function(param,div){
	param.itemType = 1;
	TX.Shift._showSingleCheck(param,"cardType;cardStatus","|openingSum;closingSum;cardSum;count",div?div:"card");
}
TX.Shift._showSingleCheck = function(param,dimension,measure,divId){
	var obj = DWR.syncCall("crosstabService.statData","counter_shift_check",dimension,measure,param);
	var crosstab = new Crosstab();
	crosstab.setData(obj);
	crosstab.show(divId);
}

TX.Misc = {};
TX.Misc.greaterThan = function(a,b){
	return (a-0)>(b-0);
}
TX.Misc.getDateBefore = function(days){
	if (!days)
		days = 1;
	var d = new Date();
		d.setTime(d.getTime()-days*24*60*60*1000);
	return d.format("yyyy-MM-dd"); 
}
/**
 * 这个方法用来检查这个array是否有任何object被赋值了
 * @param {Object} args - 一个由form object组成的array
 */
TX.Misc.hasAny = function(args){
	for(var x in args)
		if (typeof args[x] != "function" && args[x].value)
			return true;
	return false;
}
/**
 * 提供一个简单的计时器
 * init - 初始化
 * add - 添加一个时间标记
 * print - 显示计时结果
 * @param {Object} fromStart
 */
TX.Misc.Timer = {
	init:
		function(fromStart){
			TX.Misc.Timer.logs = {};
			TX.Misc.Timer.starter = (new Date()).valueOf();
			if (fromStart)
				TX.Misc.Timer.mode = true;
			else
				TX.Misc.Timer.mode = false;
		}
	,
	add:
		function(key){
			var now =  (new Date()).valueOf();
			TX.Misc.Timer.logs[key] = now - TX.Misc.Timer.starter;
			if (!TX.Misc.Timer.mode)
				TX.Misc.Timer.starter = now;
		}
	,
	print:
		function(){
			TX.Test.alertAll(TX.Misc.Timer.logs);
		}
}
TX.Test = {};
TX.Test.listTransferTarget = function(){
	var qt = new QueryTable("transfer_targets",null,"transferTargetList",[]);
	qt.paramFunc = function(){
		return {customerId:(Page.userInfo.customer?Page.userInfo.customer.id:""),
				companyCustomerId:(Page.userInfo.companyCustomer?Page.userInfo.companyCustomer.id:""),
				accCode:Page.operationForm.accCode.value,
				//unit:Account.getUnit(Page.operationForm.accCode.value),
				cardUserId:Page.userInfo.cardUser.id
				};
	}
	qt.showTable();
}
TX.Test.ToString = function(node,doNotShowNull){
	var s = ""
	for(var x in node){
		var tmp = (typeof node[x]=="function"?"[function]":node[x]);
		if (tmp && tmp.length>100)
			tmp = tmp.substring(100);
		if (doNotShowNull && tmp == null)
			continue;
		s += x+":\t"+tmp+"\n"
	}
	return s;
}
TX.Test.alertAll = function(node,doNotShowNull){
	alert(TX.Test.ToString(node,doNotShowNull));
}

var Clear = {};
//【清算部分】查询明细页面,当改动orgnization的时候,设置orgName,orgID以及orgLevel值
//为了支持xml中的HQL语句查询,form中的字段被赋予了更多和业务逻辑相关的含义:
Clear.OrgSetter = {
	Org ://受理机构改变时的回调函数
		function(v){
			return Clear.OrgSetter.setOrgAlterWithPrefix(v,"org");
		}
	,
	CardLoc ://发卡机构改变的回调函数
		function(v){
			return Clear.OrgSetter.setOrgAlterWithPrefix(v,"cardLoc");
		}
	,
	Issuer ://帐户所在机构改变的回调函数
		function(v){
			return Clear.OrgSetter.setOrgAlterWithPrefix(v,"issuer");
		}
	,
	Acquirer ://收单机构改变的回调函数
		function(v){
			return Clear.OrgSetter.setOrgAlterWithPrefix(v,"acquirer");
		}
	,
	setOrgAlterWithPrefix : 
		function (v,prefix){
			return Clear.OrgSetter._setOrgnizationAlter(v,prefix+"ID",prefix+"Name",prefix+"Level");
		}
	,
	_setOrgnizationAlter : 
		function (v,id,name,level){
			Page.form[name].value=v.name;
			Page.form[id].value=v.id;
			Page.form[level].value=v.orgLevel;
//			if(v.orgLevel>Constants.ORG_LEVEL_HQ){
//			}
//			else{
//				form[id].value = '';
//				form[level].value = '';
//			}
		}
	,
	//设置和组织机构的相关的form代码<br>
	//如orgPrefix为"foo",则本方法会会产生fooID,fooLevel两个hidden字段,fooName的input框和选择组织机构按钮
	setOrgHTML:
		function(label,orgPrefix,level){
			var option = '';
			if (level)
				option = ',{rangeLevel:' + level + '}';
			var str = "<input type='hidden' name='" + orgPrefix +"ID'>"
					+ "<input type='hidden' name='" + orgPrefix + "Level'>"
					+ "<label>" + label + "</label> <input type='text' name='" + orgPrefix
					+ "Name' readonly class='readonly' value=''>"
					+ "<a class='orga' href='#' onclick='SystemMgnt.selOrg(Page." + orgPrefix + "Setter" 
					+ option + ")'>&nbsp;&nbsp;</a>";
			$(orgPrefix).innerHTML = str;
		}
};

Clear.AccountType ={
	deposit://可以收款
		function(){
			var check = function(a){
				return a.baseAccountType == BaseAccountType.NORMAL && a.canDeposit;
			}
			return Account._getAccountTypes(check);
		}
	,
	fee://可以收款
		function(){
			var check = function(a){
				return a.baseAccountType == BaseAccountType.FEE && !a.canWithdraw;
			}
			return Account._getAccountTypes(check);
		}
	,
	foregift://卡押金
		function(){
			var check = function(a){
				return a.baseAccountType == BaseAccountType.FEE && a.canWithdraw;
			}
			return Account._getAccountTypes(check);
		}
	,
	accumulate://可以累积[HC]
		function(){
			var check = function(a){
				return a.id ==2 || a.id ==3;
			}
			return Account._getAccountTypes(check);
		}
	,
	drawback://可以退款
		function(){
			var check = function(a){
				return a.canWithdraw;
			}
			return Account._getAccountTypes(check);
		}
	,
	expire://可以失效/清零[HC]
		function(){
			var check = function(a){
				return a.id == 2;
			}
			return Account._getAccountTypes(check);
		}
	,
	transfer://转帐[TODO]
		function(){
			var check = function(a){
				return a.baseAccountType == BaseAccountType.NORMAL
			}
			return Account._getAccountTypes(check);
		}
	,
	consume:
		function(){
			var check = function(a){
				return a.id ==1 || a.id ==2;
			}
			return Account._getAccountTypes(check);
		}
	,
	load://圈存圈提
		function(){
			var check = function(a){
				return (a.hasCardAccount && a.baseAccountType == BaseAccountType.NORMAL)
			}
			return Account._getAccountTypes(check);
		}
	,
	balance://帐户余额
		function(){
			var check = function(a){
				return a.baseAccountType == BaseAccountType.NORMAL;
			}
			return Account._getAccountTypes(check);
		}
}
Clear.List = {};
//【清算部分】查询明细页面,初始化页面的公共函数
Clear.List.init = function(){
	Eui.showNavigation();
	Page = {};//页面元素Page
	Page.form = $("searchForm");//form对象
	Page.selection = ListPage._getSelection();
	Page.columns = [];//列表项
	Page.positive = true;//页面金额校验函数限制于正数
	Page.PresetOrg = {org:true,acquirer:true};//是否初始化机构控件到当前管理员所在机构
	Page.OrgLevel = {issuer:Constants.ORG_LEVEL_CITY};//默认机构选择的截止级别
	ListPage.initDateSelects();//初始化日期框
	initPageElements();//由页面定义的具体初始化内容
	Clear.List.initOrganizations();//初始化受理机构和发卡机构对象
	ListPage.initFormElements();//页面select元素的初始化
	if (Page.columns.length==0){
		if (!Page.operation)//定义页面的“操作”函数
			Page.operation = ListPage.Operations.Trade;
		Page.columns[ListPage.COLUMNS_LENGTH_MAX] = Page.operation;//设置columns中的操作项
	}
	if (!Page.defaultAccount && Page.form.accountType)
		Page.defaultAccount = Page.form.accountType.value;
	ListPage.changeAccountCode(Page.defaultAccount);//设置默认AccCode下的form元素(amount的label和校验函数等)
	setPages(["listView","detailView"]);
}

//【清算部分】查询明细页面都有受理机构和发卡机构两个查询条件
Clear.List.initOrganizations = function(){
	if($('org')){//受理
		Page.orgSetter = Clear.OrgSetter.Org;//设置处理受理机构函数
		Clear.OrgSetter.setOrgHTML("受理机构","org",Page.OrgLevel.org);
		if (Page.PresetOrg.org)
			Page.orgSetter(Common.cOrg());//默认受理机构为当前机构
	}
	if($('cardLoc')){//发卡
		Page.cardLocSetter = Clear.OrgSetter.CardLoc;
		Clear.OrgSetter.setOrgHTML("开户机构","cardLoc",Page.OrgLevel.cardLoc);
		if (Page.PresetOrg.cardLoc)
			Page.cardLocSetter(Common.cOrg());
	}
	if($('issuer')){//帐户所在
		Page.issuerSetter = Clear.OrgSetter.Issuer;//设置处理发卡机构函数
		Clear.OrgSetter.setOrgHTML("帐户所属机构","issuer",Page.OrgLevel.issuer);
		if (Page.PresetOrg.issuer)
			Page.issuerSetter(Common.cOrg());//默认无发卡机构限制
	}
	if($('acquirer')){//收单
		Page.acquirerSetter = Clear.OrgSetter.Acquirer;
		Clear.OrgSetter.setOrgHTML("收单机构","acquirer",Page.OrgLevel.acquirer);
		if (Page.PresetOrg.acquirer)
			Page.acquirerSetter(Common.cOrg());//默认无发卡机构限制
	}
}

Clear.DailyCheck ={//日结复核页面
	ONLINE_TYPE:[DailyCheckType.ONLINE
				//,DailyCheckType.ONLINE_CITY
				],
	OFFLINE_TYPE:[DailyCheckType.OFFLINE,DailyCheckType.OFFLINE_CITY],
	PERIOD_TYPE:[DailyCheckType.ONLINE,DailyCheckType.OFFLINE],
	PERIOD_STATUS:[ DailyCheckStatus.UNCHECKED,
					//DailyCheckStatus.CHECKED,
					DailyCheckStatus.ONLINE_INIT,
					DailyCheckStatus.ONLINE_CHECKED,
					DailyCheckStatus.ONLINE_MISS
					//,DailyCheckStatus.ONLINE_OK
					],
	ONLINE_STATUS:[ DailyCheckStatus.ONLINE_INIT,
					DailyCheckStatus.ONLINE_CHECKED,
					DailyCheckStatus.ONLINE_MISS,
					DailyCheckStatus.ONLINE_OK]
}
Clear.DailyCheck.init = function(){
	Eui.showNavigation();
	Page = {};//页面元素Page
	Page.form = $("searchForm");//form对象
	Page.operation = $('checkBtn');
	Page.crosstab = new Crosstab();
	Page.columns = [];//列表项
	Page.PresetOrg = {acquirer:true};//是否初始化机构控件到当前管理员所在机构
	Page.OrgLevel = {acquirer:Constants.ORG_LEVEL_CITY};//默认机构选择的截止级别
	Page.ALLOW_OVERRIDE = false;//允许跨级复核
	Page.selection = {};
	Page.selection.status = {list:Common.getItems("daily_status"),nullLabel:"全  部"};
	initPageElements();//由页面定义的具体初始化内容
	ListPage.initDateSelects();
	Page.form.startDate.value = TX.Misc.getDateBefore(Page.DEFAULT_CUTOFF+Page.DEFAULT_INTERNAL);
	Page.form.endDate.value = TX.Misc.getDateBefore(Page.DEFAULT_CUTOFF);
	Clear.List.initOrganizations();//初始化受理机构和发卡机构对象
	ListPage.initFormElements();//页面select元素的初始化
	Page.columns[ListPage.COLUMNS_LENGTH_MAX] = 
		{	title:"操作",
			width:"8%",
			align:"left",
			render:Clear.DailyCheck.operation
		};
	Page.qt = new QueryTable(Page.sql,Page.form,"datalist",Page.columns,
							{paramFunc:ListPage.paramFunc,exportable:true,buttons:Page.buttons});
	setPages(["listView","pivotView","detailView"]);
}
Clear.DailyCheck.operation = function(v,r){
	var s = "";
	var flag = Page.checkable(r);
	if (r[1].orgLevel==Constants.ORG_LEVEL_STATION)
		s += "<a href=# onclick=\"Clear.DailyCheck.showPivot('"+r[1].id+"','"+Format.dateRender(r[0].businessDate)
				+"','"+r[1].name+"',"+flag+",'"+r[0].id+"','"+r[0].status+"');return false;\">报表<\/a>";
	else
		s +="&nbsp;&nbsp;&nbsp;&nbsp;"
	if (flag)
		s += " <a href=# onclick=\"Clear.DailyCheck.check('"+r[0].id+"','"+r[1].name+"');return false;\">复核<\/a>";
	return s;
}
Clear.DailyCheck.checkOrgAuthority = function(status,type,org){
	if (status==DailyCheckStatus.CHECKED)
		return false;
	var currentOrg = Common.cOrg();
	if (type==DailyCheckType.ONLINE || type==DailyCheckType.OFFLINE){
		if(currentOrg.orgLevel>=org.orgLevel)
			return false;
		return org.parent==currentOrg.id 
					||(Page.ALLOW_OVERRIDE && org["p"+currentOrg.orgLevel]==currentOrg.id );
	}
	else if(type==DailyCheckType.ONLINE_CITY)
		return org.id==currentOrg.id 
					||(Page.ALLOW_OVERRIDE && org["p"+currentOrg.orgLevel]==currentOrg.id );
}
Clear.DailyCheck.showPivot = function (orgID,businessDate,orgName,checkable,checkId,dailyCheckStatus){
	$("statoper").innerHTML = Common.cOperator().name;
	$('dailycheckStatus').innerHTML = '当前机构日结情况:'+Common.getText('daily_status',dailyCheckStatus);
	Page.operation.disabled = (checkable?false:true);
	if (checkable)
		Page.operation.onclick = function(){
			Clear.DailyCheck.check(checkId,orgName);
		}
	var param = {};
	param.orgId = orgID;
	param.businessDate = businessDate;
	$("statTime").innerHTML = Format.today(true);
	$("statorg").innerHTML = orgName;
	$("statBusinessDate").innerHTML = param.businessDate;
	Page.showPivot(param);
}
Clear.DailyCheck.check = function(id,name,info){
	if(!info)
		info = "确认已经复核【"+name+"】的日结报表？";
	if(showQuestion(info)){
		DWR.call("dailyCheckService.confirmDailyCheck",
				id,
				function(result){
					showInformation("复核成功");
					if ($('pivotView').style.display=='none')
						Page.doQuery();
					else{
						$('dailycheckStatus').innerHTML = '当前机构复核情况:已复核';
						Page.operation.disabled = true;
					}
				},
				{blockScreen:true}
			);
	}
}
Clear.DailyCheck.goFirstPage = function(){
	switchPage('listView');
	Page.doQuery();
}

Clear.MatchResult = {};
Clear.MatchResult.getTemplate = function(){
	var map = {};
	var basic = new Array();
	basic.push(["org","商&nbsp;&nbsp;&nbsp;&nbsp;户"]);
	basic.push(["businessDate","业务日期"]);
	basic.push(["resultStatus","对帐结果"]);
	basic.push(["finishTime","统计时间"]);
//	basic.push(["clientCount","上传总笔数"]);
	basic.push(["serverCount","入帐总笔数"]);
//	basic.push(["clientAmount","上传总金额"]);
	basic.push(["serverAmount","入帐总金额"]);
//	basic.push(["clientIcCount","IC卡上传笔数"]);
	basic.push(["serverIcCount","IC卡入帐笔数"]);
//	basic.push(["clientIcAmount","IC卡上传总额"]);
	basic.push(["serverIcAmount","IC卡入帐总额"]);
//	basic.push(["clientPointCount","积分卡上传笔数"]);
	basic.push(["serverPointCount","积分卡入帐笔数"]);
//	basic.push(["clientPointAmount","积分卡上传总额"]);
	basic.push(["serverPointAmount","积分卡入帐总额"]);
//	basic.push(["clientBankCount","银行卡上传笔数"]);
	basic.push(["serverBankCount","银行卡入帐笔数"]);
//	basic.push(["clientBankAmount","银行卡上传总额"]);
	basic.push(["serverBankAmount","银行卡入帐总额"]);
	map.basic = basic;
	return map;
}
Clear.MatchResult.pretreatInfo = function(values){
	var data = {};
	for (var x in values)
		if (typeof values[x] != "function" && values[x] != null)
			data[x] = values[x];
	var renders = {	businessDate:Format.dateRender
					, finishTime:Format.timeRender
//					,clientAmount:Format.fenToYuan
					,serverAmount:Format.fenToYuan
//					,clientIcAmount:Format.fenToYuan
					,serverIcAmount:Format.fenToYuan
//					,clientPointAmount:Format.fenToYuan
					,serverPointAmount:Format.fenToYuan
//					,clientBankAmount:Format.fenToYuan
					,serverBankAmount:Format.fenToYuan}
	for (var x in renders)
		if (typeof renders[x] == "function" && data[x]!=null && typeof data[x]!="function"){
			data[x] = renders[x](data[x]);
		}
	var dicts = {resultStatus:"result_status"};
	for (var x in dicts)
		if (typeof dicts[x] != "function" && dicts[x]){
			data[x] = Common.getText(dicts[x],data[x]);
		}
	return data;
}
Clear.MatchResult.showDetail = function(id){
	DWR.call("txQueryService.getMatchResult",id,function(result){
		var str = "<table cellSpacing='0' cellPadding='4' width='100%' border='0' class='viewTable col2 label7'>";
		var data = Clear.MatchResult.pretreatInfo(result);
		var render = new DataRender(DataRender.LabelAndSpan,data);
		render.skipBlank = false;
		str += render.getItemsShowString((Clear.MatchResult.getTemplate()).basic);
		str += "</table>";
		$('matchResultDetail').innerHTML = str;
		switchPage("detailView");	
	});
}


Clear.changeTradeType = function (obj){
	var type;
	if (obj)
		type = obj.value;
	var str;
	if(type == EpsTradeType.CARD ||type == Constants.TRADE_TYPE_CARD_CONSUME || type == Constants.TRADE_TYPE_SPARE_CONSUME)
		str = "<label>卡&nbsp;&nbsp;&nbsp;&nbsp;号</label> <input type='text' name='cardAsn' value='' onblur='checkV(this,\"asn\")'>";
	else if(type == EpsTradeType.BANK || type == Constants.TRADE_TYPE_BANK_CONSUME)
		str = "<label>银行卡号<\/label> <input type='text' name='bankCard' value='' onblur=\"checkV(this,'bankCard')\">";
	else if(type==Constants.TRADE_TYPE_CHEQUE_IN ||type==Constants.TRADE_TYPE_CHEQUE_OUT)
		str = "<label>支 票 号<\/label> <input type='text' name='bankCard' value='' onblur=\"checkV(this,'checkNo')\">";
	else if(type==Constants.TRADE_TYPE_BANK_IN ||type==Constants.TRADE_TYPE_BANK_OUT)
		str = "<label>银行卡号<\/label> <input type='text' name='bankCard' value='' onblur=\"checkV(this,'bankCard')\">";
	else
		str = "";
	$("cardInfo").innerHTML = str;
}

var ListPage = {
	COLUMNS_LENGTH_MAX : 30//为了不依赖于sql的xml中column的数量,可以取个绝对的大值
	,
	showListTable : //查询明细页面,显示列表结果的公共函数
		function(){
			if (!checkForm(Page.form.id))
				return;
			if (Page.form.startDate && Page.form.endDate)
				if(!checkTimeOrder(Page.form.startDate,Page.form.endDate))
					return;
			Page.qt.showTable();
		}
	,
	initDateSelects : //查询明细页面,日期控件初始化函数
		function (){
			var form = $(Page.form.id)
			var d = new Date().format("yyyy-MM-dd")
			if ($("beginDateTd")){
				Eui.initBeginDateInput("beginDateTd","起始日期",Page.form.id,"startDate","endDate","_pastDate");
				form.startDate.value = d
			}
			if ($("endDateTd")){
				Eui.initEndDateInput("endDateTd","结束日期",Page.form.id,"startDate","endDate","_pastDate");
				form.endDate.value = d
			}
		}
	,
	initAmounts : //初始化金额限制的查询条件input框
		function(unit){
			if($("minAmountTd") && $("maxAmountTd"))
				if(unit == AccountUnit.POINT)
					Eui.initCompareInput(Page.form.id,"minAmountTd","maxAmountTd",
						"最小额(分)","最大额(分)","minMoney","maxMoney",Page.positive?"nonnegativeInt":"int","ge",false);
				else
					Eui.initCompareInput(Page.form.id,"minAmountTd","maxAmountTd",
						"最小额(元)","最大额(元)","minMoney","maxMoney",Page.positive?"nonNegativeAmount":"amount","ge",false);
		}
	,
	allowNullTradeType://设置带“全选”项目的TradeType
		function(tradeType){
			ListPage._allowNullSubSetSelection('tradeType','trade_type',tradeType);
		}
	,
	allowNullTradeStatus://设置带“全选”项目的TradeStatus
		function(status){
			ListPage._allowNullSubSetSelection('tradeStatus','trade_status',status);
		}
	,
	_allowNullSubSetSelection://根据一个子集(subset）初始化一个dict为某个select的选项,并以key为索引存入Page.selection中
		function(key,dict,subset){
			var list = Common.getSubsetItems(dict,subset);
			Page.selection[key] = {list:list,nullLabel:"全      部"};
		}
	,
	_getSelection ://默认的Page.selection。TO delete
		function(){
			var date_type = Common.getItems("time_type");
			return { dateType:{list:date_type,defText:"交易时间"}
					};
		}
}
ListPage.Operations = {
	Empty:
		{}
	,
	Trade : //明细页面的操作函数项(column)
		{title:"操作",
			width:"5%",
			align:"center",
			render:function(v,r){
						return "<a href=# onclick='DetailPage.showTrade("+r[0]+");'>明细</a>";
					}
		}
	,
	PpsTrade : //明细页面的操作函数项(column)
		{title:"操作",
			width:"5%",
			align:"center",
			render:function(v,r){
						return "<a href=# onclick='DetailPage.showPpsTrade("+r[0]+");'>明细</a>";
					}
		}
}
//查询明细页面初始化select-one元素
ListPage.initFormElements = function(){
	var length = Page.form.elements.length;
	for(var i=0;i<length;i++){
		var element = Page.form.elements[i];
		if (element.type=="select-one" && Page.selection[element.name]){
			Common._initSelect(element,Page.selection[element.name]);
		}
	}
}

/**
 * 查询明细页面,改变accCode后调用的函数
 * @param {Object} accCode
 */
ListPage.changeAccountCode = function(obj){
	var type = null;
	if (obj){//没有accCode的情况对于只有资金帐户的
		if(typeof obj == "object")
			type = obj.value;
		else
			type = obj;
	}
	var unit = Account.getUnit(type);
	//修改search form中最小/最大额的label
	ListPage.initAmounts(unit);
	//初始化Query Table中的column
	Page.qt = new QueryTable(Page.sql,Page.form,"datalist",Page.columns,
					{paramFunc:ListPage.paramFunc,exportable:true,buttons:Page.buttons});
	
}

ListPage.paramFunc= function(){//对form中的交易额根据account unit进行转换的函数
	var params = Common.getValues(Page.form);
	var transformer = Account.Transformer.InByAccCode(params.accountType);
	if (params.minMoney)
		params.minMoney = transformer(params.minMoney);
	if (params.maxMoney)
		params.maxMoney = transformer(params.maxMoney);
	params.unit = Account.getUnit(params.accountType);
	if (Page.preSubmit)
		Page.preSubmit(params);
	return params;
}
var Account = {
	getUnit : //根据accCode获取account unit
		function(accCode){
			if (!accCode)
				return AccountUnit.RMB;
			return (Common.getItem('account_type',accCode))["unit"];
		}
	,
	valueInByAccCode ://根据account的unit,当帐户操作数据进入系统时要做必要的转换
		function(accCode,value){
			var func = Account.Transformer.InByAccCode(accCode);
			return func(value);
		}
	,
	getValidatorByUnit://根据unit,返回一个校验相关form对象的函数.默认为正值校验
		function (unit,negetive){
			var type = negetive?'amount':'positiveAmount';
			if (unit == AccountUnit.POINT)
				type = negetive?'int':'positiveInt';
			return function(v){
				return checkV(v,type,true);
			};
		}
};
Account._getAccountTypes = function(check){
	var allTypes = Common.getItems('account_type');
	var list = [];
	for(var i=0;i<allTypes.length;i++){
		var a = allTypes[i];
		if (check(a))
			list.push(a);
	}
	return list;
}

Account._loadAccountTypes = function(){
	var items = DWR.syncCall("txQueryService.findAccountTypes");
	var item;
	for(var i=0;i<items.length;i++) {
		item = items[i];
		item.code = item.id				// for select usage
		item.text = item.name
	}
	return items
}

//2007-12-12,将RMB和POINT的转换统一起来
//这种情况下,翻译Trade/CardUser信息时的Renders可定义为常量
Account.Transformer = {
	InByAccCode://根据accCode,返回一个向系统内转化的数值的函数
		function(accCode){
			var func = Format.yuanToFen;
//			if (AccountUnit.POINT == Account.getUnit(accCode))
//				func = Format.emptyToZero;
			return func;
		}
	,
	OutByUnit://根据unit,返回一个向系统外转化的数值的函数
		function (unit){
			var func = Format.fenToYuan;;
//			if (unit == AccountUnit.POINT)
//				func = Format.emptyTo0;
			return func;
		}
	,
	OutByAccCode://根据unit,返回一个向系统外转化的数值的函数
		function (accCode){
			var func = Format.fenToYuan;;
//			if (AccountUnit.POINT == Account.getUnit(accCode))
//				func = Format.emptyTo0;
			return func;
		}
};

//【交易】【清算】【交易明细页面】
var DetailPage = {
	Dicts : //翻译交易明细的字典
			{tradeType:"trade_type",
			 tradeStatus:"trade_status",
			 paymentType:"pay_type",
			 accountUnit:"account_unit",
			 accountType:"account_type",
			 cardStatus:"card_status",
			 cardUserStatus:"carduser_status",
			 errorCode:"error_type"}
	,
	PpsDicts : //翻译交易明细的字典
			{tradeType:"epstrade_type",
			 tradeStatus:"epstrade_status",
			 accountUnit:"account_unit",
			 accountType:"account_type",
			 cardStatus:"card_status",
 			 adjustFlag:"adjust_type",
			 errorCode:"error_type"}
	,
	Renders : //翻译交易明细的处理函数
			{amount:Format.fenToYuan,
			 discount:Format.fenToYuan,
			 realAmount:Format.fenToYuan,
			 balance:Format.fenToYuan,
			 adjustAmount:Format.fenToYuan,
			 adjustRealAmount:Format.fenToYuan,
			 cardAsn:Format.zeroToEmpty,
			 occurTime:Format.timeRender,
			 recordTime:Format.timeRender,
			 businessDate:Format.dateRender}
	,
	showTrade : //在默认的DIV上显示一条独立的主交易明细
		function (id){
			DetailPage._divShowTrade("txQueryService.getTrade",id,"mainTrade","detailView");
		}
	,
	showPpsTrade : //在默认的DIV上显示一条异常交易明细
		function (id){
			if(!id)
				return;
			DWR.call("txQueryService.getPpsTrade",id,function(trade){
				Page.currentID = id;
				var data = DetailPage._transferPpsTradeDetails(trade);
				DetailPage.showPpsTradeDetails("mainTrade",data);
				switchPage("detailView");
			});
		}
};
DetailPage.Template = {}
//返回显示交易明细项目的map
DetailPage.Template.getGroupedTradeDetails = function(){
	var map = {};
	var basic = new Array();
	basic.push(["id","交易流水号"]);
	basic.push(["tradeStatus","交易状态"]);
	basic.push(["tradeType","交易类型"]);
	basic.push(["chequeNo","支 票 号"]);
	basic.push(["bankCard","银行卡号"]);
	basic.push(["bankTrace","银行流水号"]);
	basic.push(["occurTime","交易时间"]);
	basic.push(["recordTime","入帐时间"]);
	basic.push(["cardAsn","卡&nbsp;&nbsp;&nbsp;&nbsp;号"]);
	basic.push(["cardType","卡 类 型"]);
	basic.push(["cardUserUnique","客户编号"]);
	basic.push(["customerName","客户姓名"]);
	basic.push(["companyUnique","单位编号"]);
	basic.push(["companyName","单位名称"]);
	basic.push(["accountType","帐户类型"]);
	basic.push(["accountUnit","帐户计量单位"]);
	basic.push(["amount","交&nbsp;易&nbsp;额"]);
	basic.push(["realAmount","实际交易金额(元)"]);
	basic.push(["balance","帐户余额"]);
	basic.push(["errorCode","异常类型"])
	basic.push(["acquirerName","收单机构"]);
	basic.push(["cardLocName","开户机构"]);
	basic.push(["orgName","受理机构"]);
	basic.push(["operNo","操 作 员"]);
	map.basic = basic;
	
//	var payment = new Array();
//	payment.push(["paymentType","支付方式"]);
//	payment.push(["chequeNo","支 票 号"]);
//	payment.push(["bankCard","银行卡号"]);
//	payment.push(["bankTrace","银行流水号"])
//	map.payment = payment;
	
	var cardTx = new Array();
//	cardTx.push(["onlineTxNo","联机交易序列号"]);
//	cardTx.push(["offlineTxNo","脱机交易序列号"]);
	map.cardTx = cardTx;
	
	var accu = new Array();
	accu.push(["activityName","积分活动名称"]);
	accu.push(["ruleName","积分活动规则名称"]);
	map.accu = accu;
	
	var consume = new Array();
	consume.push(["discount","优惠/折扣金额"]);
	consume.push(["volumn","油量(升)"]);
	consume.push(["giftName","商品名称"]);
	consume.push(["giftCode","商品编号"]);
	consume.push(["goodsCategoryName","商品种类名称"]);
	consume.push(["businessDate","业务日期"]);
	consume.push(["rposNo","RPOS 编号"]);
	consume.push(["rposSn","RPOS 流水号"]);
	consume.push(["psamAsn","PSAM卡终端号"]);
	consume.push(["epsSn","EPS 流水号"]);
	map.consume = consume;
	
	var cancel = new Array();
	cancel.push(["id","撤销交易流水号"]);
	cancel.push(["operNo","撤销操作员"]);
	cancel.push(["occurTime","撤销交易时间"]);
	cancel.push(["orgName","撤销受理机构"]);
	map.cancel = cancel;
	
	var canceled = new Array();
	canceled.push(["id","原交易流水号"]);
	canceled.push(["operNo","原交易操作员"]);
	canceled.push(["occurTime","原交易时间"]);
	canceled.push(["orgName","原交易受理机构"]);
	map.canceled = canceled;
	
	return map;
}
DetailPage.Template.getSubTradeItems = function(){
	var map = {};
	var transfer = new Array();
	transfer.push(["id","交易流水号"]);
	transfer.push(["tradeType","交易类型"]);
	transfer.push(["cardAsn","卡&nbsp;&nbsp;&nbsp;&nbsp;号"]);
	transfer.push(["cardUserUnique","客户编号"]);
	transfer.push(["amount","交&nbsp;易&nbsp;额","right"]);
	transfer.push(["balance","帐户余额","right"]);
	map.transfer = transfer;
	
	var load = new Array();//暂时没用
	load.push(["id","交易流水号"]);
	load.push(["tradeType","交易类型"]);
	load.push(["amount","交&nbsp;易&nbsp;额"]);
	load.push(["balance","帐户余额"]);
	map.load = load;
	
	var consume = new Array();
	consume.push(["id","交易流水号"]);
	consume.push(["goodsCategoryName","商品种类"]);
	consume.push(["giftName","商品名称"]);
	consume.push(["amount","交&nbsp;易&nbsp;额"]);
	map.consume = consume;
	
	var exchange = new Array();
	exchange.push(["id","交易流水号"]);
	exchange.push(["acquirerName","收单机构"]);
	exchange.push(["giftCode","礼品编号"]);
	exchange.push(["giftName","礼品名称"]);
	exchange.push(["amount","兑换积分",'right']);
	exchange.push(["realAmount","实际交易金额(元)",'right']);
	map.exchange = exchange;
	return map;
}
DetailPage.Template.getPpsTradeDetails = function (){
	var basic = new Array();
	basic.push(["id","交易流水号"]);
	basic.push(["stationNo","加油站编号"]);
	basic.push(["cardAsn","卡&nbsp;&nbsp;&nbsp;&nbsp;号"]);
	basic.push(["bankNo","接入银行"]);
	basic.push(["bankCard","银行卡号"]);
	basic.push(["bankTrace","银行流水号"]);
	basic.push(["tradeType","交易类型"]);
	basic.push(["tradeStatus","交易状态"]);
	basic.push(["errorCode","异常类型"]);
	basic.push(["occurTime","交易时间"]);
	basic.push(["recordTime","入帐时间"]);
	basic.push(["businessDate","业务日期"]);
	basic.push(["accountType","帐户类型"]);
	basic.push(["balance","帐户余额"]);
	basic.push(["amount","交&nbsp;易&nbsp;额"]);
	basic.push(["amount","交易实际金额"]);
//	basic.push(["relatedId","关联交易"]);
	basic.push(["tac","TAC"]);
	basic.push(["gmac","GMAC"]);
	basic.push(["epsSn","EPS流水号"]);
	basic.push(["eftNo","EFT编号"]);
	basic.push(["rposNo","RPOS编号"]);
	basic.push(["rposSn","RPOS流水号"]);
	basic.push(["psamAsn","PSAM卡终端号"]);
	basic.push(["psamTraceNo","PSAM卡流水号"]);
	basic.push(["offlineTxNo","卡片交易序列号"]);
	basic.push(["loyaltyDate","积分有效期"]);
	basic.push(["volumn","油量(升)"]);
	basic.push(["adjustFlag","调整类型"]);
	basic.push(["adjustAmount","调&nbsp;整&nbsp;额"]);
	basic.push(["adjustRealAmount","调整实际金额"]);
	basic.push(["details","销售明细"]);
	
	return basic;
}
/**
 * 显示交易明细
 * @param {Object} showDivID
 * @param {Object} trade
 */
DetailPage.showTradeDetails = function(showDivID, trade){
	var TRADE_DETAILS = DetailPage.Template.getGroupedTradeDetails();
	var str = "<table class='viewTable col2 label8' cellSpacing='0' cellPadding='4' width='100%' border='0'>";
	var render = new DataRender(DataRender.LabelAndSpan,trade);
	str += render.getItemsShowString(TRADE_DETAILS.basic);
//	if(trade.paymentType && trade.paymentType!=0)
//		str += render.getItemsShowString(TRADE_DETAILS.payment);
	if(trade.isCardTx)
		str += render.getItemsShowString(TRADE_DETAILS.cardTx);
	//因为翻译和呈现分成了两部分,导致这里没法获取原始的TradeType
	//和tx_cl_page.js合并
	if (trade.activityName)//(trade.tradeType == Constants.TRADE_TYPE_ACCUMULATE)
		str += render.getItemsShowString(TRADE_DETAILS.accu);
	if (trade.rposSn|| trade.psamAsn || trade.giftName)//(trade.tradeType == Constants.TRADE_TYPE_CARD_CONSUME)
		str += render.getItemsShowString(TRADE_DETAILS.consume);
	if (trade.cancelTrade)
		str += render.getItemsShowString(TRADE_DETAILS.cancel,trade.cancelTrade);
	if (trade.canceledTrade)
		str += render.getItemsShowString(TRADE_DETAILS.canceled,trade.canceledTrade);
	str += "</table>";
	$(showDivID).innerHTML = str;
}
/**
 * 在默认的DIV中显示关联的子交易,并且这个div是不可折叠的
 * @param {Object} title - div的标题
 */
DetailPage.showSubTrades = function(trades){
	var title = $("subTradesTitle");
	if (title)
		title.innerHTML = "关联子交易";
	var items = DetailPage.Template.getSubTradeItems();
	var item = items.transfer;//有可能需要根据交易类型不同而选择不同的items?比如消费子类型
	if (trades[0].tradeType == Constants.TRADE_TYPE_POINT_EXCHANCE)
		item = items.exchange;
	else if (trades[0].tradeType == Constants.TRADE_TYPE_CARD_CONSUME)
		item = items.consume;
	var str = DetailPage.Misc.List2Table(trades,item,DetailPage._transferTradeDetails);
	$("subTradesList").innerHTML = str;
}
/**
 * 在指定的DIV中显示站级交易明细PpsTrade
 * @param {Object} showDivID
 * @param {Object} trade
 */
DetailPage.showPpsTradeDetails = function(showDivID, trade){
	var PPS_TRADE_DETAILS = DetailPage.Template.getPpsTradeDetails();
	var str = "<table class='viewTable col2 label8' cellSpacing='0' cellPadding='4' width='100%' border='0'>";
	var render = new DataRender(DataRender.LabelAndSpan,trade);
	str += render.getItemsShowString(PPS_TRADE_DETAILS);
	str += "</table>";
	$(showDivID).innerHTML = str;
}
/**
 * 默认的显示交易明细div方法
 * @param service - 需要调用的远程方法
 * @param id - trade ID
 * @param dataDiv - 设置数据的Div的ID
 * @param showDiv - 切换目标Div的ID（为空则表示这是条关联交易，不需要switchPage)
 */
DetailPage._divShowTrade = function(service,id,dataDiv,showDiv){
	if(!id)
		return;
	DWR.call(service,id,function(trade){
		Page.showTrade = trade;
		var data = DetailPage._transferTradeDetails(trade);
		DetailPage.showTradeDetails(dataDiv,data);
		
		var subTradesDiv = $('subTradesDiv');
		if (trade.subTrades && trade.subTrades.length>0){
			DetailPage.showSubTrades(trade.subTrades);
			subTradesDiv.style.display = "";
		}else if(subTradesDiv)
			subTradesDiv.style.display = "none";
		if (showDiv)
			switchPage(showDiv);
	});
}
/**
 * 将后台传过来的trade details信息做必要的转换
 * @param {Object} trade
 * @param {Object} handler
 */
DetailPage._transferTradeDetails = function(trade){
	return DetailPage._transferDetails(trade,DetailPage.Dicts,DetailPage.Renders);
}
DetailPage._transferPpsTradeDetails = function(trade){
	return DetailPage._transferDetails(trade,DetailPage.PpsDicts,DetailPage.Renders);
}
DetailPage._transferDetails = function(trade,dicts,renders){
	var data = {};
	for (var x in trade)
		if (typeof trade[x] != "function" && trade[x] != null)
			data[x] = trade[x];
	for (var x in dicts)
		if (typeof dicts[x] != "function" && dicts[x])
			data[x] = Common.getText(dicts[x],data[x]);
	for (var x in renders)
		if (typeof renders[x] == "function" && data[x]!=null && typeof data[x]!="function")
			data[x] = renders[x](data[x]);
	if(trade.cancelTrade)
		data.cancelTrade = DetailPage._transferDetails(trade.cancelTrade,dicts,renders);
	if(trade.canceledTrade)
		data.canceledTrade = DetailPage._transferDetails(trade.canceledTrade,dicts,renders);
	return data;
}

DetailPage.Misc = {};
/**
 * 
 * @param {Object} list - 数据List
 * @param {Object} item - 表头Columns
 * @param {Object} handler - 对list中元素的处理函数
 */
DetailPage.Misc.List2Table = function(list,item,handler){
	var str = "<table class='viewTable' cellSpacing='0' cellPadding='4' width='100%' border='0'>";
	var render = new DataRender(DataRender.SingleTr);
	render.elementsPerLine = DataRender.DynamicLine;
	str += DataRender.SingleTr.Title(item);
	var data;
	for (var x in list){
		if (list[x] && typeof list[x]!="function"){
			if(handler)
				data = handler(list[x]);
			else 
				data = list[x];
			str += render.getItemsShowString(item,data);
		}
	}
	str += "<\/table>";
	return str;
}

/**
 * DataRender用来将数据values按照render的格式呈现出来
 * @param {Object} render - 渲染器，目前有span和input两种方式
 * @param {Object} values - 包含有要呈现数据的一个Map
 * @param {Object} elementsPerLine - 每行显示的元素个数
 * @param {Object} skipBlank - 是否显示空值元素
 * @author lushu
 */
DataRender = function(render,values,elementsPerLine,skipBlank){
	this.render = render;
	this.values = values;
	this.skipBlank = skipBlank;
	this.elementsPerLine = elementsPerLine?elementsPerLine:2;
}
DataRender.testShowLabel = false;
DataRender.DynamicLine = -1;
/**
 * 根据给定的items列表,将对应的values值填充进去，并返回一个String
 * @param {Object} items - 需要呈现的items
 */
DataRender.prototype.getItemsShowString = function(items,values){
	if (!values)
		values = this.values;
	var elementsPerLine = 
		(this.elementsPerLine==DataRender.DynamicLine) ? items.length : this.elementsPerLine;
		
	var str = "";
	var j = 0;
	for(var i=0;i<items.length;i++){
		if(j%elementsPerLine == 0)
			str += "<tr>";
		var value = values[items[i][0]];
		if (value==null){
			value = "";
		}
		if(this.skipBlank && !value)//跳过空项
			continue;
		str += this.render(items[i],value);
		j++;
		if(j%elementsPerLine == 0)
			str += "<\/tr>";
	}
	if(j%elementsPerLine > 0){
		while(j%elementsPerLine > 0){
			str += "<td>&nbsp;<\/td>";
			j++;
		}
		str += "<\/tr>";
	}
	return str;
}
/**
 * 返回类似于"<td><label>label<\/label> <span>value<\/span><\/td>"的字符串
 * @param {Object} item
 * @param {Object} value
 */
DataRender.LabelAndSpan = function(item,value){
	var label = item[1];
	if(DataRender.testShowLabel)
		label += '<br>['+item[0]+']';
	var str = "<td><label>" + label + "<\/label> <span>" + value + "<\/span><\/td>";
	return str;
}
/**
 * 返回类似于"<td><label>label<\/label> <input type='text' name='item[0]' value='value' readonly class='readonly'><\/td>"的字符串
 * @param {Object} item
 * @param {Object} value
 */
DataRender.LabelAndInput = function(item,value){
	var label = item[1];
	if(DataRender.testShowLabel)
		label += '<br>['+item[0]+']';
	var str;
	if (item[2] && !value)
		str = "<td></td>";
	else{
		var readonly = " readonly class='readonly'";
		str = "<td><label>" + label + "</label> <input type='text' name='"
			+ item[0] +"' value='" + value + "'" + readonly + "><\/td>";
	}
	return str;
}
/**
 * 返回类似于"<td align='xxx'>value<\/td>"的字符串
 * @param {Object} item
 * @param {Object} value
 */
DataRender.SingleTr = function(item,value){
	var align= item[2]?item[2]:'left';
	var str = "<td align='" + align + "'>" + value + "<\/td>";
	return str;
}
DataRender.SingleTr.Title = function(item){
	var str = "<tr>";
	for(var x in item)
		if(item[x] && typeof item[x]!="function")
			str += "<td align='"+(item[x][2]?item[x][2]:'left')+"'>" + item[x][1] + "<\/td>";
	str += "<\/tr>";
	return str;
}

/**
 * 
 * @param {Object} div - 报表所在DIV
 * @param {Object} sql - 报表依据SQL
 * @param {Object} cc - CrossTabConf的初始化元素
 * @param {Object} initPivotHead - 自定义PivotHead的方法
 * @param {Object} disableConf - 关闭CrossTabConf
 * @param {Object} backFunc - 返回函数
 */
Pivot = function(div,sql,cc,option){//cc:CrossConf
	if (Pivot[div]){
		showWarning("重复报表定义");
		return;
	}
	if (!option)
		option = {};

	Pivot[div] = this;
	this.div = div;
	this.sql = sql;
	this.conf = new CrossConf();

	this.initDiv();
	$(this.div+'_conf').onclick = function(){Pivot[div].conf.openCrossConfDlg(function(){Pivot[div].saveConf()})};
	$(this.div+'_table').onclick = function(){Pivot[div].showTable()};
	$(this.div+'_chart').onclick = function(){Pivot[div].showChart(1)};
	$(this.div+'_chart2').onclick = function(){Pivot[div].showChart(2)};
	$(this.div+'_preview').onclick = function(){WebPrint.preview(div+'_printArea')};
	$(this.div+'_print').onclick = function(){WebPrint.print(div+'_printArea')};
	if (!option.backFunc)
		$(this.div+'_back').onclick = function(){switchPage('queryView')};
	else
		$(this.div+'_back').onclick = option.backFunc;
	//$(this.div+'_back2').onclick = $(this.div+'_back').onclick;
	
	if (option.disableConf)
		$(this.div+'_conf').style.display='none';
	if(cc)
		this.initConf(cc);
	if (option.initPivotHead)
		option.initPivotHead(this.div);
	else
		this.initPivotHead();
	
	this.ShowSummary = false;		//图:不显示汇总项
	this.ShowZero = false;			//图:不显示空项
	this.viewMode = this.showTable;	//默认的模式
	this.param = {};
//	this.refresh();
}
Pivot.prototype.initDiv = function(){
	var s = "<div class='form'><div class='reportBar treeBtn'>"
		+ " <a href='javascript:void(0)' id='#DIVID#_conf'><img src='../images/button/custom.gif' title='定制' align='absmiddle'>定制</a>"
		+ " <a href='javascript:void(0)' id='#DIVID#_table'><img src='../images/button/report.gif' align=absmiddle title='报表' align='absmiddle'>报表</a>"
		+ " <a href='javascript:void(0)' id='#DIVID#_chart'><img src='../images/button/histogram.gif' title='柱状图' align='absmiddle'>柱状图</a>"
		+ " <a href='javascript:void(0)' id='#DIVID#_chart2'><img src='../images/button/pie.gif' title='饼状图' align='absmiddle'>饼状图</a>"
		+ " <a href='javascript:void(0)' id='#DIVID#_preview'><img src='../images/button/preview.gif' title='打印预览' align='absmiddle'>打印预览</a>"
		+ " <a href='javascript:void(0)' id='#DIVID#_print'><img src='../images/button/print.gif' title='打印' align='absmiddle'>打印</a>"
		+ " <a href='javascript:void(0)' id='#DIVID#_back'><img id='#DIVID#_back' src='../images/button/cancel.gif' title='返回' align='absmiddle'>返回</a>"
		+ " <span id='#DIVID#_measures' style='display:none'><label>统计量</label><select id='#DIVID#_select'></select></span></div>"
		+ " <div id='#DIVID#_printArea'><div id='#DIVID#_pivot_head' align='center'></div><div align='center' id='#DIVID#_pivot_body'></div></div>"
		+ " <div id='#DIVID#_flash'></div><br></div>";
		//+"<p><button id='#DIVID#_back2'>返 回</button></p>";
	$(this.div).innerHTML = s.replace(/#DIVID#/g,this.div);
}
Pivot.prototype.initPivotHead = function(){
	var title = '<table width="100%" border="0" cellspacing="0" cellpadding="5" style="width:600">'
			  + '<tr><td align="center" class="reportTitle" height="50" colspan="2" id="#DIVID#_pivotTitle"></td></tr>'
			  + '<tr><td width="67%">统 计 人：<span id="#DIVID#_statOper"></span></td><td>统计机构：<span id="#DIVID#_statOrg"></span></td></tr>'
			  + '<tr><td>统计时间：<span id="#DIVID#_statTime"></span></td><td>报表类型：<span id="#DIVID#_statClass"></span></td></tr>'
			  + '<tr><td>起始时间：<span id="#DIVID#_beginTime"></span></td><td>结束时间：<span id="#DIVID#_endTime"></span></td></tr></table>';
	$(this.div+'_pivot_head').innerHTML = title.replace(/#DIVID#/g,this.div);
	this.setPivotHead('pivotTitle',document.title);
	this.setPivotHead('statOper',Common.cOperator().name);
	this.setPivotHead('statOrg',Common.cOrg().name);
}
Pivot.prototype.setPivotHead = function(key,value){
	$(this.div+'_'+key).innerHTML = value;
}
Pivot.prototype.initConf = function(cc){
	this.cc = cc;
	this.conf.initCrosstab(cc.dimensions,cc.measures,cc.defaultHorizon,cc.defaultVertical,cc.defaultMeasure);
	var list = [];
	for(var x in cc.measures)
		if (cc.measures[x] && typeof(cc.measures[x])!="function")
			list.push({code:x,text:cc.measures[x]});
	var defCode = this.conf.getChartMeasures();
	defCode = defCode.substring(1,defCode.indexOf(';'));
	var pivot = Pivot[this.div];
	Common._initSelect($(this.div+'_select'),{list:list,defCode:defCode,onchange:function(){pivot.refresh()}});
}
Pivot.prototype.saveConf = function(){
	this.cc.defaultMeasure = this.conf.getCurrentMeasure();
	this.cc.defaultVertical = this.conf.getCurrentVertical();
	this.cc.defaultHorizon = this.conf.getCurrentHorizon();
	this.refresh();
}
Pivot.prototype.refresh = function(){
	if(this.cc)
		this.viewMode();
}

Pivot.prototype.showTable = function(){
	this.viewMode = this.showTable;
	$(this.div+'_flash').style.display='none';
	$(this.div+'_measures').style.display='none';
	$(this.div+'_printArea').style.display='';
	var rows = this.conf.getDimensions();
	var cols = this.conf.getMeasures();//Common.getValue($(this.div+'_select'))//
	var target = this.div+'_pivot_body';
	var obj = DWR.syncCall("crosstabService.statData", this.sql, rows, cols, this.param);
	var crosstab = new Crosstab();
	crosstab.setData(obj);
	crosstab.show(target);
	
}
Pivot.prototype.showChart = function(type){
	this.viewMode = this.showChart;
	if (type)
		this.chartType = type;
	$(this.div+'_printArea').style.display='none';
	$(this.div+'_measures').style.display='';
	$(this.div+'_flash').style.display='';
	var rows = this.conf.getChartDimensions();
	var measure = ($(this.div+'_select')).value;
	var cols = '|'+measure+';';//this.conf.getChartMeasures();
	var obj = DWR.syncCall("crosstabService.statData", this.sql, rows, cols, this.param);
	this.FusionCharts(obj);
}
Pivot.prototype.FusionCharts = function (obj){
	var skipSum = !this.ShowSummary;
	var skipZero = !this.ShowZero;
	var rows = obj.rowTitles;
	var columns = obj.columnTitles;
	var data = obj.dataMatrix;
	if (data.length != obj.measureSize){
		showError('数据错误:数据集维度不一致');
		return;
	}
	var measure = obj.dimensions.slice(-1*obj.measureSize);
	var chartData = new Array();

	if(this.chartType == 1)
		this.chart = new FusionCharts2DColumn();//可能和measure的个数有关,所以在方法内赋值
	else if(this.chartType == 2)
		this.chart = new FusionChart2DPie();
	this.chart.div = this.div+'_flash';
	
	if (obj.rowSize==0 && obj.columnSize==0){
		showError("未设置统计维度");
		return;
	}else if (obj.rowSize==0 || obj.columnSize==0){
// 				if(Page.chartType == 1)
//					chart = new FusionCharts2DColumn();
//				else if(Page.chartType == 2)
//					chart = new FusionChart2DPie();
		var single = rows.length==0?columns:rows;
		creation:
			for(var j=0;j<single.length;j++){
				var x = single[j];
				if (skipSum)
					for(var t=0;t<x.length;t++)
						if(x[t]==null)
							continue creation;
				var d = '['+x.join('][')+']';
				for(var k=0;k<measure.length;k++){
					if (skipZero && data[k][j]==0)
						continue creation;
					chartData.push([d,measure[k].title,data[k][j]]);
				}
			}
	}else{
//				if(Page.chartType == 1)
//					chart = new FusionCharts2DColumn();
//				else if(Page.chartType == 2)
//					chart = new FusionChart2DPie();
		creation:
			for(var i=0;i<rows.length;i++){
				for(var j=0;j<columns.length;j++){
					var x = rows[i].concat(columns[j]);
					if (skipSum)
						for(var t=0;t<x.length;t++)
							if(x[t]==null)
								continue creation;
					var d = x.join();
					for(var k=0;k<measure.length;k++){
						if (skipZero && data[k][i][j]==0)
							continue creation;
						chartData.push([d,measure[k].title,data[k][i][j]]);
					}
				}
			}
	}
	if(chartData[0] == null){
		showWarning('没有数据');
		return;
	}
	//this.chart.setAndShow(chartData);
	var length = obj.dimensions.length;
	var measure = obj.dimensions[length-1].name;
	//var unit = (obj.dimensions[length-1].name=='count')?'':'Yuan元'
	var xAxis = '';
	for(var i = 0;i<length-1;i++)
		xAxis += '['+obj.dimensions[i].title+']'
	this.chart.setSingleData(chartData);
	//this.chart.setAttribute("graph@caption",chartData[0][1]);
	//this.chart.setAttribute("graph@yAxisName",unit);
	this.chart.setAttribute("graph@xAxisName",xAxis);
	if (measure=='sum' ||measure=='realAmount' ||measure=='cost'){
		this.chart.setAttribute("graph@yAxisName","Yuan");
		this.chart.setAttribute("graph@numberPrefix",'￥');
		this.chart.setAttribute("graph@decimalPrecision",2);
	}else if(measure=='volumn'){
		this.chart.setAttribute("graph@yAxisName","Litre");
		this.chart.setAttribute("graph@decimalPrecision",2);
	}else{
		this.chart.setAttribute("graph@decimalPrecision",0);
	}
	//alert(this.chart.getXML());
	this.chart.show();
	return;
	
}

var PivotPage = {
	getBeginAndEndDate:
		function (statType){
			if(statType == Constants.CLEAR_STAT_DYNA)
				return [Format.getBeginTimeOfDay(Page.form.beginDate.value),
							Format.getEndTimeOfDay(Page.form.endDate.value)];
			else{
				var sDate = Page.form.statDate.value;
				if(statType == Constants.CLEAR_STAT_DAY)
					return [Format.getBeginTimeOfDay(sDate),Format.getEndTimeOfDay(sDate)];
				else if(statType == Constants.CLEAR_STAT_MONTH)
					return [Format.getBeginTimeOfMonth(sDate),Format.getEndTimeOfMonth(sDate)];
				else if(statType == Constants.CLEAR_STAT_YEAR)
					return [Format.getBeginTimeOfYear(sDate),Format.getEndTimeOfYear(sDate)];
			}
		}
	,
	setOrg:
		function (param,prefix,org){
			if (!org)
				org = Page.org;
			param[prefix+"ID"] = org.id;
			param[prefix+"Level"] = org.orgLevel;
		}
	,
	_initPivot:
		function(){
			Page.pivot = new Pivot("pivotView",Page.sql);
			Page.pivot.ShowSummary = Page.ShowSummary;
			Page.pivot.ShowZero = Page.ShowZero;
		}
	,
	_defaultShowPivot:
		function(){
			var param = PivotPage._getParam();
			Page.statClass = Common.getRadioValue("statClass")-0;//统计方式
			Page.orgSpec.setOrgnizations(Page.statClass,param);		//设置查询的机构参数
		
			Page.pivot.initConf(Page.crosstabConfSet[Page.statClass]);
			Page.pivot.param = param;
			Page.pivot.setPivotHead('statTime',Format.today(true));
			Page.pivot.setPivotHead('statClass',Page.statClass?Common.getText('stat_class',Page.statClass):"无");
			Page.pivot.setPivotHead('beginTime',param.beginDate);
			Page.pivot.setPivotHead('endTime',param.endDate);
			Page.pivot.refresh();
		}
	,
	_getParam:
		function(){
			var param = {};
			if (Page.tradeType && Page.tradeType.length>1){//交易类型
				param.beginType = Page.tradeType[0];
				param.endType = Page.tradeType[1];
			}else
				param.tradeType = Page.tradeType;
				
			if(Page.accountType && Page.accountType.length>1){//帐户类型
				param.beginAccType = Page.accountType[0];
				param.endAccType = Page.accountType[1];
			}else
				param.accType = Page.accountType;
				
			var statType = Common.getRadioValue("statType");//统计时间类型
			var dates = PivotPage.getBeginAndEndDate(statType);//统计时间
			param.beginDate = dates[0];
			param.endDate = dates[1];
			return param;
		}
}
PivotPage.CrosstabConf = {
	getClearingResultConf:
		function(){
			var temp = {};
			temp.measures = {sum:"交易额",count:"交易数"};
			temp.defaultMeasure = {sum:true,count:true};
			temp.dimensions = {
				businessDate:{name:"时间",option:{year:"年份",quarter:"季度",month:"月份"}},
				acquirer:{name:"收单机构",option:{p200:"省大区",p500:"地市",p700:"站级机构"}},
				org : {name:"受理机构",option:{p200:"省大区",p500:"地市",p700:"站级机构"}},
				issuer:{name:"帐户所属机构",option:{p200:"省大区",p500:"地市"}},
				tradeType:"交易类型",
				tradeStatus:"交易状态",
				cardUserType:"客户类型",
				cardUserLevel:"客户级别",
				cardType:"卡类型",
				bank:"银行"};
			temp.defaultVertical = {};
			temp.defaultHorizon = {acquirer:{},org:{},issuer:{},tradeType:false,tradeStatus:false,accountType:false};
			return temp;
		}
	,
	getPpsTradeConf:
		function(){
			var temp = {};
			temp.measures = {realAmount:"实际金额",sum:"交易额",volumn:"油量(升)",count:"交易数"};
			temp.defaultMeasure = {realAmount:true,count:true};
			temp.dimensions = {
				businessDate:{name:"时间",option:{year:"年份",quarter:"季度",month:"月份"}},
				org : {name:"受理机构",option:{p200:"省大区",p500:"地市",p700:"站级机构"}},
				tradeType:"交易类型",
				accountType:"帐户类型",
				status:"交易状态",
				errorCode:"异常类型",
				adjustFlag:"调整类型"};
			temp.defaultVertical = {};
			temp.defaultHorizon = {org:{},tradeType:true,accountType:true};
			return temp;
		}
	,
	getDealedTradeConf:
		function (){
			var crossconf = {};
			crossconf.measures = {realAmount:"实际金额",sum:"交易额",volumn:"油量(升)",count:"交易数"};
			crossconf.defaultMeasure = {realAmount:true,count:true};
			crossconf.dimensions = {
						businessDate:{name:"时间",option:{year:"年份",quarter:"季度",month:"月份"}},
						org:{name:"受理机构",option:{p200:"省大区",p500:"地市",p700:"站级机构"}},
						acquirer:{name:"收单机构",option:{p200:"省大区",p500:"地市",p700:"站级机构"}},
						accountType:'帐户类型',tradeType:'交易类型',tradeStatus:'交易状态',errorCode:"错误代码"
						,cardUserType:"客户类型",cardUserLevel:"客户级别",cardType:"卡类型",bank:'银行'
					};
			crossconf.defaultVertical = {};
			crossconf.defaultHorizon = {org:{},accountType:true,tradeType:true,errorCode:true};
			return crossconf;
		}
}
PivotPage.OrgSpec = {
	presetConf :
		function(orgSpec,statClass){
			var temp = orgSpec._getDefaultConf(statClass);
			if (Page.tradeTypeSpec)
				Page.tradeTypeSpec(temp,orgSpec.LEVEL);
			Page.crosstabConfSet[statClass] = temp;
		}
	,
	getSpecOrg :
		function(orgLevel){
			switch(orgLevel){
				case Constants.ORG_LEVEL_HQ:
					return PivotPage.OrgSpec.Headquarter;
					break;
				case Constants.ORG_LEVEL_PROVINCE:
					return PivotPage.OrgSpec.Province;
					break;
				case Constants.ORG_LEVEL_CITY:
					return PivotPage.OrgSpec.City;
					break;
			}
		}
};
PivotPage.OrgSpec.Headquarter = {
	LEVEL:
		Constants.ORG_LEVEL_HQ
	,
	STAT_CLASS:{
		FULL:[StatClass.Headquarter],
		LOCAL:[StatClass.Headquarter],
		BENDAITA:[StatClass.Headquarter],
		CONSUME:[StatClass.Headquarter,StatClass.Org]
	}
	,
	_getDefaultConf:
		function(statClass){
			var temp = PivotPage.CrosstabConf.getClearingResultConf();
			switch(statClass){
				case StatClass.Headquarter:
					temp.defaultHorizon.acquirer = {p200:true};
					temp.defaultHorizon.issuer = {p200:true};
					break;
				case StatClass.Org:
					break;
				default:
					showWarning("未知统计方式");
			}
			return temp;
		}
	,
	setOrgnizations:
		function(statClass,param){
			switch(statClass){
				case StatClass.Headquarter:
					param.headQuarter = true;
					break;
				default:
					showWarning("未知统计方式");
			}
		}
}
PivotPage.OrgSpec.Province = {
	LEVEL:
		Constants.ORG_LEVEL_PROVINCE
	,
	STAT_CLASS:{
		FULL:[StatClass.Acquirer,StatClass.BenDaiTa,StatClass.TaDaiBen],
		LOCAL:[StatClass.Acquirer],
		BENDAITA:[StatClass.BenDaiTa],
		CONSUME:[StatClass.Org,StatClass.TaDaiBen]
	}
	,
	_getDefaultConf:
		function(statClass){
			var temp = PivotPage.CrosstabConf.getClearingResultConf();
			switch(statClass){
				case StatClass.Acquirer:
					temp.defaultHorizon.acquirer = {p500:true};
					break;
				case StatClass.BenDaiTa:
					temp.defaultHorizon.acquirer = {p500:true};
					temp.defaultHorizon.issuer = {p200:true};
					break;
				case StatClass.TaDaiBen:
					temp.defaultHorizon.acquirer = {p200:true};
					break;
			}
			return temp;
		}
	,
	setOrgnizations:
		function(statClass,param){
			switch(statClass){
				case StatClass.Acquirer:
					PivotPage.setOrg(param,Page.orgNameForParam);
					PivotPage.setOrg(param,'issuer');
					break;
				case StatClass.BenDaiTa:
					PivotPage.setOrg(param,'acquirer');
					PivotPage.setOrg(param,'benDaiTa');
					break;
				case StatClass.TaDaiBen:
					PivotPage.setOrg(param,'issuer');
					PivotPage.setOrg(param,'taDaiBen');
					break;
				default:
					showWarning("未知统计方式");
			}
		}
}

PivotPage.OrgSpec.City = {
	LEVEL:
		Constants.ORG_LEVEL_CITY
	,
	STAT_CLASS:{
		FULL:[StatClass.Acquirer,StatClass.BenDaiTa],
		LOCAL:[StatClass.Acquirer],
		BENDAITA:[StatClass.BenDaiTa],
		CONSUME:[StatClass.Org]
	}
	,
	_getDefaultConf :
		function(statClass){
			var temp = PivotPage.CrosstabConf.getClearingResultConf();
			switch(statClass){
				case StatClass.Acquirer:
					temp.defaultHorizon.org = {p700:true};
					break;
				case StatClass.BenDaiTa:
					temp.defaultHorizon.org = {p700:true};
					temp.defaultHorizon.issuer = {p200:true};
					break;
			}
			return temp;
		}
	,
	setOrgnizations:
		function(statClass,param){
			switch(statClass){
				case StatClass.Acquirer:
					PivotPage.setOrg(param,'org');
					PivotPage.setOrg(param,'issuer',Page.parentOrg);
					break;
				case StatClass.BenDaiTa:
					PivotPage.setOrg(param,'org');
					PivotPage.setOrg(param,'benDaiTa',Page.parentOrg);
					break;
				default:
					showWarning("未知统计方式");
			}
		}
}

PivotPage.init = function(){
	Eui.showNavigation();
	Page = {};
	Page.ShowSummary = false;		//图:不显示汇总项
	Page.ShowZero = false;			//图:不显示空项
	Page.DEFAULT_DAY = 1;			//默认日期,昨天
	Page.org = Common.cOrg();
	Page.orgSpec = PivotPage.OrgSpec.getSpecOrg(Page.org.orgLevel);
	if (Page.org.orgLevel == Constants.ORG_LEVEL_CITY){
		var result = DWR.syncCall("partyService.getOrganization", Page.org.parent);
		Page.parentOrg = result.organization;
	}
	
	Page.form = $("statForm");
	Page.crosstab = new Crosstab();
	Page.sql = "clearing_results";
	
	initPageElements();
	Eui.showStatBtn("stat_btn",null,{
		form:Page.form,
		statFunc:PivotPage.doQuery
	});
	Page.orgNameForParam = Page.useOrg?"org":"acquirer";	//统计时根据“受理机构”还是“收单机构”限制查询结果
	Page.crosstabConfSet = [];
	for (x in Page.statSets)
		if(Page.statSets[x] && typeof(Page.statSets[x])!='function'){
			PivotPage.OrgSpec.presetConf(Page.orgSpec,Page.statSets[x]);
		}
	
	if(Page.statSets)
		Common.initBoxOrRadio("statClass",{
				list:Common.getSubsetItems("stat_class",Page.statSets),
				name:"text", value:"code",isRadio:"true",defChecked:Page.statSets[0]
			}
		);
	Page.form.statDate.value = TX.Misc.getDateBefore(Page.DEFAULT_DAY); 
	
	if (Page.initPivot)
		Page.initPivot();
	else
		PivotPage._initPivot();
	setPages(["queryView","pivotView"]);
}

PivotPage.doQuery = function (){
	if (!checkForm(Page.form.id))
		return;

	if (Page.showPiovt)
		Page.showPiovt();
	else
		PivotPage._defaultShowPivot();
		
	switchPage("pivotView");
}
Common.registerSpecialDict('account_type', Account._loadAccountTypes);
